#!/bin/sh

rssfile="/home/counter/counter/www/linuxcounternews.rss"
newrssfile="/home/counter/counter/www/linuxcounternews.rss-new"
rsstagfile="/home/counter/counter/temp/rss-tags"
itemsadded=0
today=`date +%Y%m%d`

>$newrssfile
>$rsstagfile

cat /home/counter/counter/www/news.php | grep "<\!--" | cut -c 6- >> $rsstagfile

if [ "`grep \<item\> $rssfile`" = "" ]
then
	# No news item in rssfile
	search_for="</channel>"
else
	# New item should be first item in file
	search_for="<item>"
fi

i=`cat $rsstagfile | wc -l`

cat /home/counter/counter/www/linuxcounternews.rss | 
while read line
do
	if [ "`echo $line | grep "$search_for"`" = "" ]
	then
		echo $line >> $newrssfile
	else
		if [ $itemsadded = 0 ]
		then
			for (( k=1 ; k<=$i ; k++ ))
			do
				newsitem="`head -$k $rsstagfile | tail -1`"
				if [ "`echo $newsitem | awk -F ':' '{ print $1 }'`" = "RSS-TAG" -a `echo $newsitem | awk -F ':' '{ print $2 }'` -eq $today ]
				then
					title="`echo $newsitem | awk -F ':' '{ print $3 }'`"
					description="`echo $newsitem | awk -F ':' '{ print $4 }'`"
					url="http://counter.li.org/`echo $newsitem | awk -F ':' '{ print $5 }'`"

					echo "  <item>" >> $newrssfile
					echo "    <title>$title</title>" >> $newrssfile
					echo "    <description>$description</description>" >> $newrssfile
					echo "    <link>$url</link>" >> $newrssfile
					echo "  </item>" >> $newrssfile
					echo "" >> $newrssfile
				fi
			done

			echo $line >> $newrssfile

			itemsadded=1
		else
			echo $line >> $newrssfile
		fi
	fi
done

cp $newrssfile $rssfile
chmod 644 $rssfile
chown counter.counter $rssfile

